<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>补卡</title>
    <link rel="stylesheet" href="../utils/bootstrap-5.3.3-dist/css/bootstrap.min.css">
    <script src="../utils/bootstrap-5.3.3-dist/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../utils/icon/iconfont.css">
    <link rel="stylesheet" href="../css/shared.css">
    <style>
        /*中部布局*/
        .central-layout {
            display: grid;
            grid-template-rows: 40px 550px;
            width: 100%;
            margin: 0 auto;
        }
        /*中部底部布局*/
        .central-bottom-layout {
            display: grid;
            grid-template-rows: 70px 450px 50px;
            width: 80vw;
            margin: 0 auto;
        }
    </style>
</head>
<body>
<div class="body-grid">
    <!--头部-->
    <div class="header-grid">
        <!--    返回按钮-->
        <div>
            <!--            <button class="btn btn-secondary iconfont go-back-button" onclick="window.location.href='card-issuance.html';">-->
            <!--                &#xe623;-->
            <!--            </button>-->
        </div>
        <!--    标题-->
        <div class="page-title" id="page-title">
            <script>
                document.getElementById("page-title").innerText=window.sessionStorage.getItem("competitionName")
                +"--补卡"
            </script>
        </div>
        <div></div>
    </div>
    <!--中部-->
    <div class="central-layout">

        <div>
            <!--        顶部导航-->
            <div class="btn-group">
                <button type="button" class="btn btn-primary" onclick="window.location.href='batch.html'">批次管理</button>
                <button type="button" class="btn btn-primary" onclick="window.location.href='rule.html'">规则设置</button>
                <button type="button" class="btn btn-primary" onclick="window.location.href='start-game.html'">开始比赛</button>
                <button type="button" class="btn btn-primary" onclick="window.location.href='calculate-score.html'">成绩计算</button>
                <button type="button" class="btn btn-primary" onclick="window.location.href='replace-card.html'">补卡</button>
            </div>
        </div>

        <div class="central-bottom-layout">
            <div>
                <!--                搜索框组件-->
                <div style="width: 600px;margin: auto">
                    <div class="input-group">
                        <input id="search-input" type="text" class="form-control" placeholder="可按选手姓名、组别、单位名称、指卡号进行搜索">
                        <button class="btn btn-outline-secondary iconfont" type="button" onclick="showSearch()">&#xe60a;
                        </button>
                    </div>
                    
                </div>
                <div style="float:right;">
                    <span id="makeCardMsg2" style="margin-left:10px;color:red;display:none;">请连接读卡器设备</span>
                    <span id="makeCardMsg" style="margin-left:10px;color:red;display:none;">请放置指卡</span> 
                </div>
            </div>

            <div class="table-responsive">
                <table id="r-card-table" class="table table-sm table-bordered text-center">
                    <thead>
                    <tr>
                        <th>新指卡号</th>
                        <th>原指卡号</th>
                        <th>姓名</th>
                        <th>组别</th>
                        <th>性别</th>
                        <th>参赛单位</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="r-card-tbody" class="table-group-divider">
                    </tbody>
                </table>
            </div>
            <div >
                <!--    分页组件-->
                <ul class="pagination page-ul-flex" id="pagination">
                </ul>
            </div>
        </div>

    </div>
    <!--尾部-->
    <div class="footer-grid" style="margin: 15px;">
        <!--网格留空-->
        <div></div>
        <!--进度条-->
        <div id="progress-bar" class="progress-bar-flex">
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">新增赛事</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">新增项目</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">设置组别</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">导入选手</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">下发号码</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">制卡</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">签到</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">批次管理</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">规则设置</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">开始比赛</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">成绩计算</div>
                <i class="iconfont progress-bar-arrow" style="visibility: hidden;">&#xe604;</i>
            </div>
        </div>
        <!--   占位不能删-->
        <div>
        </div>
    </div>
</div>
<script src="../js/pages.js"></script>
<script src="../api/urls.js"></script>
<script src="../js/dialog.js"></script>
<script src="../js/progress.js"></script>
<script src="../js/request.js"></script>

<script>
    updateProgress("progress-bar",REPLACE_CARD_PROGRESS);

    //页码
    let pageNum = 1;
    //一页多少条
    let pageSize = 9;
    //总条数
    let total;
    //总页数
    let pages;
    //请求记录
    let records;
    //搜索内容
    let searchAll;
    //选手id
    let athleteId;
    //赛事id
    let competitionId;

    let btnList = [];
   

    window.onload = async function () {
        competitionId=window.sessionStorage.getItem("competitionId")
        //每次刷新页面必须关闭串口，以防之前打开的串口未被关闭
        await closePort()
    }

    //websocket双向通信请求
    function websocketConnect() {
        const ws_url = WEBSOCKET_BASE_URL + competitionId;
        socket = new WebSocket(ws_url)

        socket.onopen = async function () {

            var makeCardBtn = document.getElementById("makeCardBtn" + athleteId)
            var makeCardMsg = document.getElementById('makeCardMsg')
            var makeCardMsg2 = document.getElementById('makeCardMsg2')
            let res = await openPort()

            if (res.code !== '200') {
                //断开连接并关闭串口
                await socket.close()
                makeCardMsg2.style.display=''
                    
                
            }else{
                
                makeCardBtn.onclick = closeWebsocket
                makeCardBtn.innerText = "结束录入"
                makeCardBtn.className = "btn btn-danger btn-sm"

                makeCardMsg.style.display = ''
                makeCardMsg.innerText = '请放置指卡'
                makeCardMsg2.style.display='none'
                
                //将其他的btn禁用
                for(var i=0;i<btnList.length;i++){
                    if(!(btnList[i] == "makeCardBtn" + athleteId)){
                        document.getElementById(btnList[i]).disabled='disabled'
                    }
                }
            }

        }

        socket.onmessage = async function (event) {
            var makeCardMsg = document.getElementById('makeCardMsg')
            makeCardMsg.innerText=event.data
            if(event.data==='读卡结束......'){
                await socket.close()
                await showPage();

            }
           
        }

        socket.onclose = async function () {
            await closePort()
            socket = null

            var makeCardBtn = document.getElementById("makeCardBtn" + athleteId)
            var makeCardMsg = document.getElementById('makeCardMsg')
            makeCardBtn.onclick = websocketConnect

            makeCardBtn.innerText = "\u{e6f7}补卡"
            makeCardBtn.className = "btn btn-primary btn-sm iconfont"
            makeCardMsg.style.display = 'none'

            //将其他的btn禁用
            for(var i=0;i<btnList.length;i++){
     
                if(!(btnList[i] == "makeCardBtn" + athleteId)){
                    document.getElementById(btnList[i]).disabled=''
                }
            }
            
        }

        socket.onerror = function () {
            socket.close()
        }

    }

    //串口通信打开请求
    async function openPort() {
        let url = new URL(BASE_URL+'/cardWebsocket/openReplacePort')
            url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"))
            url.searchParams.set("athleteId", athleteId)
        let res = await fetch_http({
            url: url,
            method: 'get'
        })
        return res
    }

    //串口通信关闭请求
    async function closePort() {
        let url = new URL(BASE_URL+'/cardWebsocket/closePort')
        let res = await fetch_http({
            url: url,
            method: 'get',
        })
        return res
    }

    //关闭websocket
    async function closeWebsocket() {
        //断开连接并关闭串口,改变按钮状态
        socket.close()
    }

    /**
     * 点击搜索
     */
    async function showSearch() {
        pageNum = 1;
        await showPage();
    }

    /**
     * 渲染表格
     */
    function drawReplaceCardTable(records) {
        let tableBody = document.getElementById("r-card-tbody");
        tableBody.innerHTML = "";
        for (let record of records) {
            let trElement = document.createElement("tr");
            let tdElement1 = document.createElement("td");
            tdElement1.textContent = record.newCardNum;
            let tdElement2 = document.createElement("td");
            tdElement2.textContent = record.oldCardNum;
            let tdElement3 = document.createElement("td");
            tdElement3.textContent=record.athleteName;
            let tdElement4 = document.createElement("td");
            tdElement4.textContent=record.groupName;
            let tdElement5 = document.createElement("td");
            tdElement5.textContent = record.gender;
            let tdElement6 = document.createElement("td");
            tdElement6.textContent = record.unitName;
            let tdElement11 = document.createElement("td");
            let buttonElement1 = document.createElement("button");
            buttonElement1.classList.add("btn", "btn-primary", "btn-sm", "iconfont");
            buttonElement1.textContent = "\u{e6f7}补卡";
            buttonElement1.id='makeCardBtn'+record.athleteId;
            btnList.push("makeCardBtn"+record.athleteId)
            buttonElement1.addEventListener('click', () => {
                athleteId = record.athleteId
            });
            buttonElement1.onclick=websocketConnect

            tdElement11.append(buttonElement1);
            trElement.append(tdElement1, tdElement2, tdElement3, tdElement4, tdElement5,tdElement6, tdElement11);
            tableBody.append(trElement);
        }
    }

    //实现分页的方法
    async function getPage(pageNum, pageSize) {
        let searchInput = document.getElementById("search-input");
        searchAll = searchInput.value;
        let url = new URL(CARD_URL + "/replaceCardSearchAll");
        url.searchParams.set("pageNum", pageNum);
        url.searchParams.set("pageSize", pageSize);
        url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        url.searchParams.set("searchAll", searchAll);
        await fetch(url).then(response => {
            if (response.ok && response.headers.get("Content-Type") === "application/json") {
                return response.json();
            } else {
                throw new Error(`未知相应状态 ${response.status}或Content-Type：${response.headers.get("Content-Type")}`);
            }
        }).then(pageInfo => {
            pages = pageInfo.pages;
            total = pageInfo.total;
            records = pageInfo.records;
            drawReplaceCardTable(records);
        }).catch(error => {
            console.log("分页错误：", error);
        });
    }

    //上一页
    async function prePage() {
        pageNum = pageNum - 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    //下一页
    async function nextPage() {
        pageNum = pageNum + 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages)
    }

    //点击切换
    async function handlePage(page) {
        if (page !== pageNum) {
            pageNum = page
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages);
        }

    }

    /**
     * 改变每页条数
     */
    async function changePageSize(value) {
        pageSize = Number(value);
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    // 创建分页组件
    async function showPage() {
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }
    if (window.sessionStorage.getItem("competitionId")) {
        (async () => {
            await showPage();
        })();
    }

</script>
</body>
</html>